package SparkSteaming

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

object SparkKfk {

  def main(args: Array[String]): Unit = {
    /*spark streaming实现kafka的消费者
    1）构建sparkconf 本地运行，运行应用程序名称
    2）构建sparkstreaming ---》streamingContext, 加载配置

    3）kafka配置broker,key value,group id,消费模式
    4）spark链接kafka 订阅，topic,streamingcontext
    5)循环的形式 打印/处理
    6）开启ssc,监控  kafka  数据
    */
    val conf = new SparkConf().setMaster("local[*]").setAppName("sssssss")
    //StreamingContext需要导入依赖
    //spark streaming 可以进行流式处理，微批次处理，间隔2秒
    val ssc = new StreamingContext(conf, Seconds(2))

    //3）kafka配置broker,key value,group id,消费模式
    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "192.168.238.99:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false: java.lang.Boolean))
    //4）spark链接kafka 订阅，topic,streamingcontext
    val topicName = Array("15homework")
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicName, kafkaParams)
    )
    //5)循环的形式 打印/处理
    streamRdd.foreachRDD {
      x => {
        if (!x.isEmpty()) {
          val line = x.map(_.value())
          line.foreach(println)
        }
      }
    }
    //6）开启ssc,监控  kafka  数据
    ssc.start()
    ssc.awaitTermination()
  }
}
